<?php

namespace app\admin\controller\manager;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class User extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model            = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp      = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;

                //unset($groups[0]);
            }
            $groupdata = $result;

        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // $where['createtime'] = $where['t_createtime'];
            // unset($where['t_createtime']);
            //dump($where);
            //
            $join[] = ["auth_group_access group_access", "a.id = group_access.uid"];
            $join[] = ["auth_group g", "g.id = group_access.group_id"];
            $field  = "a.id,a.username,a.nickname,a.status status,a.createtime ,a.role,g.pid,g.name,a.platform";
            $total  = Db::name('admin')->alias("a")->join($join)->field($field)->where($where)->count();
            $list   = Db::name('admin')->alias("a")->join($join)->field($field)->where($where)->limit($offset, $limit)->select();
            foreach ($list as &$value) {
                if ($value['platform'] == 1) {
                    $value['platform'] = '总管理后台';
                }
                if ($value['platform'] == 2) {
                    $value['platform'] = '商户后台';
                }
                if ($value['status'] === 'normal') {
                    $value['status'] = '正常';
                } else {
                    $value['status'] = '禁用';
                }
                $value['group'] = $value['name'];
            }
            //dump($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['salt']     = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar']   = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $params['email'] = '';
                //这里需要针对username和email做唯一验证
                //$adminValidate = \think\Loader::validate('Admin');
                if ($params['platform'] == 2) {
                    if(empty($params['bank_name'])){
                        $this->error('开户行名称不能为空');
                    }
                    if(empty($params['bank_username'])){
                        $this->error('开户人名字不能为空');
                    }
                    if(empty($params['bank_account'])){
                        $this->error('开户行账号不能为空');
                    }
                }

                $result = $this->model->validate('Admin.add')->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $group = $this->request->post("group/a");

                //过滤不允许的组别,避免越权
                $group   = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    $params['salt']     = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|max:50|unique:admin,username,' . $row->id,
                    //'email'    => 'require|email|unique:admin,email,' . $row->id,
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids  = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList        = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    protected function selectpage()
    {
        $this->dataLimit      = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

    /**
     * 密码重置
     * @Author   chenjianghui
     * @DateTime 2018-09-03T14:14:42+0800
     * @return   [type]                   [description]
     */
    public function resetpsw($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params['password']) {
                $params['salt']     = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            } else {
                unset($params['password'], $params['salt']);
            }
            $result = $row->save($params);
            if ($result !== false) {
                return json(['code' => 1, 'msg' => '密码重置成功']);
                renderJson("密码重置成功", 1);
            } else {
                return json(['code' => 0, 'msg' => '密码重置失败']);
                renderJson("密码重置失败", 0);
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function update_status()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            //dump($params);die;
            $status = "";
            if ($params) {
                switch ($params["field"]) {
                    case "status":
                        $status = $params["status"] == '正常' ? 'hidden' : 'normal';
                        break;
                }
                try {
                    $res = $this->model->save([$params["field"] => $status], ["id" => $params["id"]]);
                    renderJson("成功:" . json_encode($params), 1);
                } catch (\Exception $e) {
                    renderJson("失败", 0);
                }

            }
        }
    }

}
